package ClientServer;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;

import GUI.ServerConsoleGUI;
import ocsf.server.AbstractServer;
import ocsf.server.ConnectionToClient;
import server.DBHandller;

public class ServerSide extends AbstractServer {
/* Variables */
	int DEFUALT_PORT  =  ProtocolIF.DEFAULT_PORT;	
	private DBHandller rDBHandller;
	static ServerConsoleGUI SCG;
	
/**** -------- constructors ---------- ****/
	public ServerSide(int port) {
		super(port);
		
		// TODO Auto-generated constructor stub
	}



@Override
protected void handleMessageFromClient(Object msg, ConnectionToClient client) {
	// TODO Auto-generated method stub
	// System.out.println("Message received: " + msg + " from " + client);
	if (msg instanceof ArrayList){
		{
		
			rDBHandller.InsertDataToDb("products",((ArrayList) msg).get(0).toString(),((ArrayList) msg).get(1).toString(),((ArrayList) msg).get(2).toString());
			try {
				client.sendToClient("added To db");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	else if (((String)msg).compareTo("BringDB")==0)
	{
		ResultSet msg1 = rDBHandller.getTable("products");
		try {
			try {
				while(msg1.next())
				{
					 // Print out the values
					client.sendToClient(msg1.getString(1)+" | " +msg1.getString(2)+" |"+msg1.getString(3)+" |"+msg1.getString(4));
				}
				msg1.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//client.sendToClient(rs);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
		SCG.setMessageToScreen("Message received: " + msg + " from " + client);
	    this.sendToAllClients(msg);
	  }

// Implemented Hook to handle proccess on startup of the server
protected void serverStarted()
{
	SCG.setMessageToScreen("Server listening for connections on port " + getPort());
	Connect2DB();
	IPConfig();
		
}
private void Connect2DB(){
	String Host="localhost",DB="ass2",username="root",password="godmode";
	try {
		Scanner in = new Scanner(new FileReader("DBConfig.txt"));
		in.useDelimiter(",");
		while (in.hasNext()){
			Host = in.next();
			DB =  in.next();
			username = in.next();
			password = in.next();
		}
		System.out.println(Host+" "+DB+" "+username+" "+password );
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		SCG.setMessageToScreen("Colud not read configuration file to connect the database.. restart the server application please");
		SCG.setMessageToScreen("Termanting in...");
		for (int i=1; i<=5 ; i++){
			SCG.setMessageToScreen("In :"+i+" sec");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		System.exit(0);
		e.printStackTrace();
	}
	
	rDBHandller = new DBHandller(Host,DB,username,password); // connects to db 
	SCG.setMessageToScreen("DB connection sucsecsful");
	
}
protected void serverStopped()
{
 // System.out.println
 //   ("Server has stopped listening for connections.");
	 SCG.setMessageToScreen("Server has stopped listening for connections.");
	 
  //DB close Connection
}

public static void main(String[] args) 
{
  int port = 0; //Port to listen on

  
    port =  ProtocolIF.DEFAULT_PORT; //Set port to 6001
    SCG = new ServerConsoleGUI();
    ServerSide sv = new ServerSide(port);
  
  try 
  {
    sv.listen(); //Start listening for connections
  } 
  catch (Exception ex) 
  {
    //System.out.println("ERROR - Could not listen for clients!");
	  SCG.setMessageToScreen("ERROR - Could not listen for clients!");
  }
  
}

private void IPConfig(){
	Runtime r = Runtime.getRuntime();
	try {
		Process p = r.exec("ipconfig ");
		
		BufferedReader in = new BufferedReader(new
				InputStreamReader(p.getInputStream()));
				String inputLine;
				
				while ((inputLine = in.readLine()) != null) {
				//System.out.println(inputLine);
					SCG.setMessageToScreen(inputLine);
					String pingResult = inputLine;
				}
				in.close();
		
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}//catch
}
	
}
